package com.bdqn.rooms.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.bdqn.rooms.beans.Rooms;
import com.bdqn.rooms.service.RoomsService;
import com.bdqn.rooms.util.PageInfo;
import com.bdqn.rooms.util.Result;
import com.bdqn.rooms.util.ResultUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jack
 * @since 2019-05-14
 */
@Controller
@RequestMapping("/rooms")
public class RoomsController {
    @Resource
    private RoomsService roomsServiceImpl;
    /**
     * 显示房间添加页面
     * @return
     */
    @RequestMapping("/roomPage")
    public String showPage(){
        return "RoomPage";
    }

    /**
     * 添加房间
     * @param rooms
     * @param imgurl
     * @return
     */
    @RequestMapping("/addRooms")
    @ResponseBody
    public Result addRooms(Rooms rooms, HttpServletRequest request,
                           @RequestParam(value = "imgurl",required = false)MultipartFile[] imgurl){
        ArrayList<String> imgUrlList= new ArrayList<String>();
        for(int i = 0; i< imgurl.length; i++){
            String image= imgurl[i].getOriginalFilename();
            imgUrlList.add(image);
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
            File targetfile= new File(path,image);
            if(!targetfile.exists()){
                targetfile.mkdir();
            }
            try {
                imgurl[i].transferTo(targetfile);
            } catch (IOException e) {
                e.printStackTrace();
                ResultUtil.error();
            }

        }
        String imgeStr = JSON.toJSONString(imgUrlList);
        rooms.setImgesurl(imgeStr);
        roomsServiceImpl.insert(rooms);
        return ResultUtil.success(rooms.getRuserid());
    }

    /**
     * 分页查询房间
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/selRooms")
    @ResponseBody
    public PageInfo<Rooms> selRooms(String page,String limit){
        PageInfo<Rooms> rooms=new PageInfo<Rooms>();
        Page<Rooms> roomsPage = roomsServiceImpl.selRooms(page, limit);
        rooms.setCount(roomsPage.getTotal());
        rooms.setData(roomsPage.getRecords());
        return rooms;
    }

}

